﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using SoccerEvaluator.Common;
using System.Web.UI.HtmlControls;
using SoccerEvaluator.Business;

namespace SoccerEvaluator.WebSite
{

    /// <summary>
    /// 
    /// </summary>
    public partial class MatchCreator : System.Web.UI.Page
    {
        /// <summary>
        /// 
        /// </summary>
        public SystemUserInfo User
        {
            get
            {
                if (Session["user"] != null)
                {
                    SystemUserInfo u = (SystemUserInfo)Session["user"];

                    return u;
                }
                else return null;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        private TemplateInfo Result
        {
            get
            {

                if (this.Session["result"] == null)
                {
                    TemplateInfo r = new TemplateInfo();
                    r.Scores = new List<ScoreInfo>();

                    this.Session["result"] = r;
                }

                return (TemplateInfo)this.Session["result"];
            }
            set { this.Session["result"] = value; }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this.RadDatePicker1.SelectedDate = DateTime.Now;

                string[] files = System.IO.Directory.GetFiles(Server.MapPath(@"~\Teams"), "*.jpg");

                Array.Sort(files);

                FileInfo fInfo = null;

                foreach (string f in files)
                {
                    fInfo = new FileInfo(f);
                    this.cmbLocal.Items.Add(fInfo.Name.Replace(".jpg", ""));
                    this.cmbVisitor.Items.Add(fInfo.Name.Replace(".jpg", ""));
                }

                //Si hay proyecto que cargar para editar
                if (Request.QueryString["project"] != null && User != null)
                {
                    string projectName = Request.QueryString["project"].ToString();

                    string pathDirectory = string.Format(@"{0}\{1}", Server.MapPath(@"~\Projects"), projectName);

                    string pathFile = string.Format(@"{0}\{1}.xml", pathDirectory, projectName);

                    Template loader = new Template();

                    this.Result = loader.LoadResult(pathFile);

                    this.txtProjectName.ReadOnly = true;

                    this.cmdAdd.Enabled = false;
                    this.cmdDelete.Enabled = false;
                }

                if (this.Result != null)
                {
                    this.txtProjectName.Text = this.Result.Name;
                    int index = this.cmbProjectMode.FindItemIndexByValue(this.Result.ProjectMode.ToString());
                    this.cmbProjectMode.SelectedIndex = index;
                    this.txtExactScore.Text = this.Result.ExactScore.ToString();
                    this.txtCatchScore.Text = this.Result.CatchScore.ToString();


                    this.lstScores.DataSource = this.Result.Scores;
                    this.lstScores.DataBind();
                }

                this.cmbProviders.DataSource = Business.ScoreUpdater.ListProviders(Server.MapPath("~/Providers"));
                this.cmbProviders.DataBind();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void cmdAdd_Click(object sender, EventArgs e)
        {
            ScoreInfo score = new ScoreInfo();

            score.Local = this.cmbLocal.Text;
            score.Visitor = this.cmbVisitor.Text;
            score.Date = this.RadDatePicker1.SelectedDate.HasValue ? this.RadDatePicker1.SelectedDate.Value : DateTime.MinValue;
            score.Location = this.txtLocation.Text;

            this.Result.Scores.Add(score);

            this.lstScores.DataSource = this.Result.Scores;
            this.lstScores.DataBind();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lstScores_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem != null)
            {
                ScoreInfo s = (ScoreInfo)e.Item.DataItem;

                HtmlTableRow row = (HtmlTableRow)e.Item.FindControl("row");

                if (s.Enabled == 0)
                {
                    row.Attributes.Add("class", "Deactivated");
                }
                else
                {
                    row.Attributes.Add("class", "ScoreLine");
                }


                TextBox tLocal = (TextBox)e.Item.FindControl("txtLocalGoals");

                if (tLocal != null)
                {
                    tLocal.Text = s.LocalGoals.ToString();
                }

                TextBox tvisitor = (TextBox)e.Item.FindControl("txtVisitorGoals");

                if (tvisitor != null)
                {
                    tvisitor.Text = s.VisitorGoals.ToString();
                }


                CheckBox cEnabled = (CheckBox)e.Item.FindControl("");

                if (cEnabled != null)
                {
                    cEnabled.Checked = s.Enabled == 1;
                }

                tLocal.ReadOnly = s.Enabled == 0;
                tvisitor.ReadOnly = s.Enabled == 0;

            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void cmdDelete_Click(object sender, EventArgs e)
        {
            if (this.Result.Scores.Count > 0)
            {
                this.Result.Scores.RemoveAt(this.Result.Scores.Count - 1);

                this.lstScores.DataSource = this.Result.Scores;
                this.lstScores.DataBind();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void cmdCreateProject_Click(object sender, EventArgs e)
        {
            if (this.User != null)
            {
                this.Result.Name = this.txtProjectName.Text;
                this.Result.ProjectMode = int.Parse(this.cmbProjectMode.SelectedItem.Value);
                this.Result.RegisterDate = DateTime.Now;
                this.Result.ExactScore = int.Parse(this.txtExactScore.Text);
                this.Result.CatchScore = int.Parse(this.txtCatchScore.Text);
                this.Result.User = User.Username;


                //Actualiza los marcadores de futbol
                this.UpdateScores(this.Result.Scores);

                UserResult fMan = new UserResult();

                string pathDirectory = string.Format(@"{0}\{1}", Server.MapPath(@"~\Projects"), this.Result.Name);

                if (!fMan.Exists(pathDirectory))
                {
                    fMan.CreateDirectory(pathDirectory, this.Result.Name);
                }

                Template loader = new Template();

                string pathFile = string.Format(@"{0}\{1}.xml", pathDirectory, this.Result.Name);

                loader.SaveResult(pathFile, this.Result.Name, this.Result);

                //Borra para que al ingresar nuevamente entre como formulario nuevo
                this.Result = null;

                Response.Redirect("MatchList.aspx");
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="list"></param>
        private void UpdateScores(List<ScoreInfo> list)
        {
            for (int i = 0; i < list.Count; i++)
            {
                RepeaterItem item = this.lstScores.Items[i];

                TextBox tLocal = (TextBox)item.Controls[0].FindControl("txtLocalGoals");
                TextBox tVisitor = (TextBox)item.Controls[0].FindControl("txtVisitorGoals");

                list[i].LocalGoals = int.Parse(tLocal.Text);
                list[i].VisitorGoals = int.Parse(tVisitor.Text);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void cmdUpdateScores_Click(object sender, EventArgs e)
        {
            int year = int.Parse(this.txtYear.Text);
            int month = int.Parse(cmbMonth.SelectedValue);

            string providerName = this.cmbProviders.SelectedValue; ;

            DateTime d = new DateTime(year, month, 1);

            string path = string.Format(@"{0}{1}.xml", Server.MapPath("~/Providers/"), providerName);

            lstProviderScores.DataSource=Business.ScoreUpdater.GetScores(path, d);
            lstProviderScores.DataBind();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lstProviderScores_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem != null)
            {
                ScoreInfo s = (ScoreInfo)e.Item.DataItem;

                HtmlTableRow row = (HtmlTableRow)e.Item.FindControl("row");

                if (s.Enabled == 0)
                {
                    row.Attributes.Add("class", "Deactivated");
                }
                else
                {
                    row.Attributes.Add("class", "ScoreLine");
                }


                HtmlImage imgStadium = (HtmlImage)e.Item.FindControl("imgStadium");

                string imgFile = Server.MapPath("~/Locations/" + s.Location + ".jpg");

                if (File.Exists(imgFile))
                {
                    imgStadium.Src = string.Format(@"~/Locations/{0}.jpg", s.Location);
                }
            }
        }
    }
}


